package cn.shengchao.controler.wecom;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeUserInviteService;
import cn.shengchao.examstar.me.collect.acl.ports.repositories.IUserCollectInfoRepository;
import cn.shengchao.examstar.me.infrastructure.dao.po.UserCollectInfo;
import cn.shengchao.qywx.infrastrure.po.*;
import cn.shengchao.qywx.infrastrure.service.*;
import cn.shengchao.rule.base.ActionType;
import cn.shengchao.rule.base.ConditionGroup;
import cn.shengchao.rule.condition.paramKey.IConditionParamKey;
import cn.shengchao.rule.engine.RuleEngine;
import cn.shengchao.util.helper.LoginHelper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.continew.starter.web.model.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: examstarapi
 * @description: 企微业务
 * @author: Xiong weiqiang
 * @create: 2025-04-14 10:30
 */

@RestController
@Slf4j
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/qywx")
@RequiredArgsConstructor
public class QywxContactMeController {
    private final IUserCollectInfoRepository userCollectInfoRepository;
    private final QywxSysCsGroupUserbindService qywxSysCsGroupUserbindService;
    private final DistributeUserInviteService distributeUserInviteService;
    private final QywxUserServiceInviteService qywxUserServiceInviteService;
    private final QywxUserSysbindService qywxUserSysbindService;
    private final QywxRuleGroupService qywxRuleGroupService;
    private final QywxContactMeLoader contactMeLoader;
    private final QywxCustomerQrcodeLockerService qywxCustomerQrcodeLockerService;
    @SaIgnore
    @PostMapping("/getRuleContactMe")
    public R<String> getRuleContactMe(@RequestBody Map<String,String> targetValueMap ) throws Exception{
        if (targetValueMap==null){
            targetValueMap=new HashMap<>();
        }
        Long uid=-1L;
        try {
            //获取当前登录用户信息
            uid = LoginHelper.getLoginUser().getId();
        } catch (NotLoginException e) {
        }
        Map<String,String> returnMap=new HashMap<>();
        if (uid>0){
            UserCollectInfo userCollectInfo= userCollectInfoRepository.getUserCollectInfo(uid);
            targetValueMap.put(IConditionParamKey.VIP_LEVELS,userCollectInfo.getVipLevel()==null?"0":userCollectInfo.getVipLevel().toString());
            targetValueMap.put(IConditionParamKey.USER_SOURCE_CHANNEL,userCollectInfo.getSourceChanel()==null?"-1":userCollectInfo.getSourceChanel());
            targetValueMap.put(IConditionParamKey.REGISTER_DATE_RANGE,userCollectInfo.getRegisterTime()==null?"": DateUtil.format(userCollectInfo.getRegisterTime(),"yyyyMMdd"));
            List<ConditionGroup> conditionGroups =RuleEngine.executeRules(targetValueMap);
            System.out.println("匹配规则："+conditionGroups.size()+"条"+ JSONUtil.toJsonStr(conditionGroups));
            for (ConditionGroup conditionGroup:conditionGroups){
                String qrCode= getGroupQrCodeLocker(conditionGroup,uid);
                if (StrUtil.isNotBlank(qrCode)){
                    System.out.println("锁码匹配：条件组："+conditionGroup.getGroupId()+",json:"+JSONUtil.toJsonStr(conditionGroup));
                    returnMap.put("qrCode",qrCode);
                    return R.ok(returnMap);
                }else {
                    System.out.println("非锁码匹配：条件组："+conditionGroup.getGroupId()+",json:"+JSONUtil.toJsonStr(conditionGroup));
                    ContactMeResult contactMeResult = contactMeLoader.getContactMe(conditionGroup,uid);
                    if (contactMeResult.getQywxUserQrcode()!=null){
                        returnMap.put("qrCode",contactMeResult.getQywxUserQrcode());
                        return R.ok(returnMap);
                    }
                }
            }
        }

        String code=contactMeLoader.getPlatFormContactMe(uid).getQywxUserQrcode();
        returnMap.put("qrCode",code);
        System.out.println("返回平台所属："+code);
        return R.ok(returnMap);
    }

    /**
     * 二维码锁码有没有
     * @param conditionGroup
     * @param uid
     * @return
     */
    private String getGroupQrCodeLocker(ConditionGroup conditionGroup, Long uid){
        String groupQrCodeState=contactMeLoader.getGroupQrCodeState(conditionGroup==null?0L:conditionGroup.getGroupId());
        List<QywxCustomerQrcodeLocker> customerQrcodeLockerList = qywxCustomerQrcodeLockerService.list(
                Wrappers.lambdaQuery(QywxCustomerQrcodeLocker.class)
                        .eq(QywxCustomerQrcodeLocker::getUserId,uid)
                        .eq(QywxCustomerQrcodeLocker::getQrState,groupQrCodeState)
                        .eq(QywxCustomerQrcodeLocker::getLockStatus,1)
        );

        if (CollectionUtil.isNotEmpty(customerQrcodeLockerList)){
            String assignUserId = customerQrcodeLockerList.getFirst().getRuleUserId();
            //判断锁码成员是否还生效。
            if (ObjUtil.isNotNull(conditionGroup)){
                //如果存在规则匹配，判断是否在绑定关系中
                if (conditionGroup.getAction().getActionType().equals(ActionType.SPECIFIC_USER)){
                    QywxRuleGroup group=qywxRuleGroupService.getById(conditionGroup.getGroupId());
                    //匹配上
                    if (group!=null&&group.getActionValue()!=null&&group.getActionValue().equals(assignUserId)){
                        return customerQrcodeLockerList.getFirst().getQrCode();
                    }else{
                        return null;
                    }
                }else if (conditionGroup.getAction().getActionType().equals(ActionType.INVITER)){
//                    List<DistributeUserInvite> list=distributeUserInviteService.list(Wrappers.lambdaQuery(DistributeUserInvite.class)
//                            .eq(DistributeUserInvite::getUserId,uid).eq(DistributeUserInvite::getDataStatus,1));
                    List<QywxUserServiceInvite> list=qywxUserServiceInviteService.list(Wrappers.lambdaQuery(QywxUserServiceInvite.class)
                            .eq(QywxUserServiceInvite::getUserId,uid).eq(QywxUserServiceInvite::getDataStatus,0));
                    if (CollUtil.isNotEmpty(list)&&list.size()==1){
                        long count=qywxUserSysbindService.count(
                                Wrappers.lambdaQuery(QywxUserSysbind.class).eq(QywxUserSysbind::getSysUserId,list.getFirst().getServiceUserId())
                                        .eq(QywxUserSysbind::getQywxUserId,assignUserId)
                                );
                        if (count==0){
                            qywxCustomerQrcodeLockerService.update(
                                    Wrappers.lambdaUpdate(QywxCustomerQrcodeLocker.class)
                                            .eq(QywxCustomerQrcodeLocker::getUserId,uid)
                                            .eq(QywxCustomerQrcodeLocker::getRuleUserId,assignUserId)
                                            .set(QywxCustomerQrcodeLocker::getLockStatus,2)
                            );
                            return null;
                        }
                        //匹配上
                        return customerQrcodeLockerList.getFirst().getQrCode();

                    }
                    return null;
                }else {
                    //检查是否在绑定关系中
                    long count=qywxSysCsGroupUserbindService.count(Wrappers.lambdaQuery(QywxSysCsGroupUserbind.class)
                            .eq(QywxSysCsGroupUserbind::getCsGroupId,(conditionGroup.getAction().getActionValue()))
                            .eq(QywxSysCsGroupUserbind::getQywxUserId,assignUserId)
                    );
                    if (count==0){
                        qywxCustomerQrcodeLockerService.update(
                                Wrappers.lambdaUpdate(QywxCustomerQrcodeLocker.class)
                                        .eq(QywxCustomerQrcodeLocker::getUserId,uid)
                                        .eq(QywxCustomerQrcodeLocker::getRuleUserId,assignUserId)
                                        .set(QywxCustomerQrcodeLocker::getLockStatus,2)
                        );
                        return null;
                    }
                    return customerQrcodeLockerList.getFirst().getQrCode();
                }
            }else{
                //默认兜底规则是客服组
                //检查是否在绑定关系中
                long count=qywxSysCsGroupUserbindService.count(Wrappers.lambdaQuery(QywxSysCsGroupUserbind.class)
                        .eq(QywxSysCsGroupUserbind::getCsGroupId,0L)
                        .eq(QywxSysCsGroupUserbind::getQywxUserId,assignUserId)
                );
                if (count==0){
                    qywxCustomerQrcodeLockerService.update(
                            Wrappers.lambdaUpdate(QywxCustomerQrcodeLocker.class)
                                    .eq(QywxCustomerQrcodeLocker::getUserId,uid)
                                    .eq(QywxCustomerQrcodeLocker::getRuleUserId,assignUserId)
                                    .set(QywxCustomerQrcodeLocker::getLockStatus,2)
                    );
                    return null;
                }
                return customerQrcodeLockerList.getFirst().getQrCode();
            }

        }
        return null;
    }
}